package com.china08.yxyapi.api.manage.tec.teaching.weikecheng.upload;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResTemp;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResTempRepository;

import io.swagger.annotations.ApiOperation;

/**
 * 根据md5查看视频文件是否存在 如果存在 返回文件存储的位置 如果不存在 在文件上传完成后 在返回文件地址
 * 
 * 
 * @author Json
 *
 */
@CrossOrigin
@RestController
public class WeikechengCheckController extends YxyApiBaseController {

    @Autowired
    private YxyResResourceRepository yxyResResourceRepository;

    @Autowired
    private YxyResTempRepository yxyResTempRepository;

    @ApiOperation("根据md5查询视频")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/weikecheng/check", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req) {
        List<YxyResResource> list = yxyResResourceRepository.findByMd5OrderByUploadTimeAsc(req.md5);
        RespModel respModel = new RespModel();
        if (CollectionUtils.isNotEmpty(list)) {
            respModel.location = list.get(0).getLocation();
            respModel.status = 1;
        } else {
            YxyResTemp resTemp = yxyResTempRepository.findByMd5(req.md5);
            if (resTemp != null) {
                respModel.location = resTemp.getLocation();
                respModel.status = 1;
            }
        }

        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {

        public String md5;// 微课md5

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(md5, null), "视频md5不能为空");
        }

    }

    protected static class RespModel extends YxyApiRespModel {
        public Integer status = 0;
        public String location;
    }

}